package gu.simplemq.mqtt;

import gu.simplemq.Constant;
import gu.simplemq.pool.BaseMQInstance;

/**
 * MQTT对象工厂类用于获取producer/consumer,publisher/subscriber,table对象<br>
 * 应用程序结束时会自动清除所有subscriber和consumer
 * @author guyadong
 *
 */
public class MqttFactory implements Constant {

	private MqttFactory() {}
	private static final BaseMQInstance<MqttSubscriber,MqttPoolLazy> SUBSCRIBERS = 
			new BaseMQInstance<MqttSubscriber,MqttPoolLazy>(){
		@Override
		protected void beforeDelete(MqttSubscriber r) {
			try {
				r.close();
			} catch (Throwable e) {
				e.printStackTrace();
			}
	}};
	private static final BaseMQInstance<MqttPublisher,MqttPoolLazy> PUBLISHERS = 
			new BaseMQInstance<MqttPublisher,MqttPoolLazy>(){};
	/**
	 * 返回 {@link MqttPoolLazy}对应的{@link MqttSubscriber}实例
	 * @param poolLazy
	 * @return {@link MqttSubscriber}实例
	 */
	public static MqttSubscriber getSubscriber(MqttPoolLazy poolLazy) {
		return SUBSCRIBERS.getInstance(poolLazy);
	}
	/** 
	 * 返回{@link MqttPoolLazy}默认实例对应的{@link MqttSubscriber}实例
	 * @see  {@link MqttPoolLazy#getDefaultInstance()}
	 * @return {@link MqttSubscriber}实例
	 */
	public static MqttSubscriber getSubscriber() {
		return SUBSCRIBERS.getInstance(MqttPoolLazys.getDefaultInstance());
	}
	/**
	 * 返回 {@link MqttPoolLazy}对应的{@link MqttPublisher}实例
	 * @param poolLazy
	 * @return {@link MqttPublisher}实例
	 */
	public static MqttPublisher getPublisher(MqttPoolLazy poolLazy) {
		return PUBLISHERS.getInstance(poolLazy);
	}
	/** 
	 * 返回{@link MqttPoolLazy}默认实例对应的{@link MqttPublisher}实例
	 * @see  {@link MqttPoolLazy#getDefaultInstance()}
	 * @return {@link MqttPublisher}实例
	 */
	public static MqttPublisher getPublisher() {
		return PUBLISHERS.getInstance(MqttPoolLazys.getDefaultInstance());
	}
	/**
	 * 关闭并删除所有consumer,subscriber,producer
	 */
	public synchronized static void closeAll(){
		SUBSCRIBERS.clearInstances();
	}
	static {
		// JVM 结束时自动清除所有consumer和subscriber,producer对象
		Runtime.getRuntime().addShutdownHook(new Thread(){

			@Override
			public void run() {
				try {
					closeAll();
					// 销毁连接池对象
					MqttPoolLazys.closeAll();
				} catch (Throwable e) {
					logger.error(e.toString());
				}
			}			
		});
	}
}
